<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElNotification } from 'element-plus';
import { UserFilled, Lock, Warning, DataBoard, Monitor, Connection } from '@element-plus/icons-vue';
import { login } from '@/api/user';
import { useUserStore } from '@/stores/user';

const router = useRouter();
const userStore = useUserStore();

// 登录表单
const loginForm = reactive({
  username: '',
  password: ''
});

// 表单规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
};

const formRef = ref(null);
const loading = ref(false);
const rememberMe = ref(false);
const loginError = ref('');
const capsLockOn = ref(false);

// 检测大写锁定
const checkCapsLock = (e) => {
  capsLockOn.value = e.getModifierState && e.getModifierState('CapsLock');
};

// 登录方法
const handleLogin = async () => {
  // 清除之前的错误信息
  loginError.value = '';
  
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        const response = await login(loginForm.username, loginForm.password);
        
        if (response && response.data && response.data.token) {
          console.log('登录响应数据:', response.data);
          
          // 设置token和用户信息到store
          userStore.setToken(response.data.token);
          userStore.setUserInfo({
            username: response.data.username,
            name: response.data.name,
            email: response.data.email,
            role: response.data.role || '管理员'
          });
          
          // 验证token是否保存成功
          const savedToken = localStorage.getItem('token');
          console.log('保存的token:', savedToken);
          
          // 如果选择记住我，保存用户名
          if (rememberMe.value) {
            localStorage.setItem('username', loginForm.username);
          } else {
            localStorage.removeItem('username');
          }
          
          // 显示成功通知
          ElNotification({
            title: '登录成功',
            message: `欢迎回来，${response.data.name || response.data.username}！`,
            type: 'success',
            duration: 3000
          });
          
          // 确保token保存后再跳转
          setTimeout(async () => {
            const finalToken = localStorage.getItem('token');
            console.log('跳转前检查token:', finalToken);
            if (finalToken) {
              await router.push('/dashboard');
            } else {
              console.error('Token保存失败，无法跳转');
              ElMessage.error('登录状态保存失败，请重试');
            }
          }, 800);
        } else {
          loginError.value = '登录失败，请检查用户名和密码';
          ElMessage.error('登录失败，请检查用户名和密码');
        }
      } catch (error) {
        console.error('登录失败:', error);
        loginError.value = error.message || '登录失败，请检查用户名和密码';
        ElMessage.error(loginError.value);
      } finally {
        loading.value = false;
      }
    } else {
      return false;
    }
  });
};

// 检查是否有记住的用户名
const checkRememberedUser = () => {
  const rememberedUsername = localStorage.getItem('username');
  if (rememberedUsername) {
    loginForm.username = rememberedUsername;
    rememberMe.value = true;
  }
};

// 键盘回车登录
const handleKeyDown = (e) => {
  if (e.key === 'Enter') {
    handleLogin();
  }
};

// 页面加载时检查
onMounted(() => {
  checkRememberedUser();
  
  // 添加键盘事件监听
  document.addEventListener('keydown', handleKeyDown);
  
  // 检查是否是从登出跳转过来的
  const logoutMessage = sessionStorage.getItem('logoutMessage');
  if (logoutMessage) {
    ElNotification({
      title: '退出成功',
      message: logoutMessage,
      type: 'success',
      duration: 3000
    });
    sessionStorage.removeItem('logoutMessage');
  }
  
  // 组件卸载时移除事件监听
  return () => {
    document.removeEventListener('keydown', handleKeyDown);
  };
});
</script>

<template>
  <div class="login-container">
    <!-- 左侧品牌宣传区域 -->
    <div class="login-background">
      <div class="platform-info">
        <div class="platform-logo">
          <span class="logo-text">SpringBoot</span>
          <div class="logo-badge">示例系统</div>
        </div>
        <div class="platform-slogan">
          <h2>现代化开发 · 高效构建 · 快速部署</h2>
          <p>基于SpringBoot + Vue3的全栈开发示例项目</p>
        </div>
        <div class="platform-features">
          <div class="feature-item">
            <el-icon><DataBoard /></el-icon>
            <span>数据管理</span>
          </div>
          <div class="feature-item">
            <el-icon><Monitor /></el-icon>
            <span>系统监控</span>
          </div>
          <div class="feature-item">
            <el-icon><Connection /></el-icon>
            <span>Redis缓存</span>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 右侧登录区域 -->
    <div class="login-content">
      <div class="login-panel">
        <div class="login-header">
          <h1>欢迎登录</h1>
          <p>请使用您的账号密码登录系统</p>
        </div>
        
        <el-form 
          ref="formRef" 
          :model="loginForm" 
          :rules="rules" 
          class="login-form" 
          @keyup.enter="handleLogin">
          
          <!-- 错误提示 -->
          <el-alert 
            v-if="loginError" 
            :title="loginError" 
            type="error" 
            :closable="true" 
            show-icon 
            class="login-error animated shake" 
            @close="loginError = ''" />
          
          <!-- 用户名输入框 -->
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              :prefix-icon="UserFilled"
              clearable
              :disabled="loading"
              size="large"
              @keyup="checkCapsLock" />
          </el-form-item>
          
          <!-- 密码输入框 -->
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              :prefix-icon="Lock"
              show-password
              clearable
              :disabled="loading"
              size="large"
              @keyup="checkCapsLock" />
            <div v-if="capsLockOn" class="caps-lock-warning">
              <el-icon><Warning /></el-icon> 大写锁定已开启
            </div>
          </el-form-item>
          
          <!-- 登录选项 -->
          <div class="login-options">
            <el-checkbox v-model="rememberMe" :disabled="loading">记住密码</el-checkbox>
            <el-link type="primary" :underline="false" class="forgot-password">忘记密码?</el-link>
          </div>
          
          <!-- 登录按钮 -->
          <el-button 
            type="primary" 
            :loading="loading" 
            class="login-button" 
            @click="handleLogin">
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
          

        </el-form>
        
        <!-- 底部版权信息 -->
        <div class="login-footer">
          <p>© {{ new Date().getFullYear() }} SpringBoot示例项目 by Logan.Li</p>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 登录页面整体布局 */
.login-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  background-color: #f0f2f5;
  margin: 0;
  padding: 0;
  z-index: 1000;
}

/* 左侧品牌宣传区域 */
.login-background {
  width: 55%;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
  flex-shrink: 0;
}

.login-background::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><circle cx="50" cy="50" r="2" fill="rgba(255,255,255,0.1)"/></svg>') repeat;
  animation: float 20s ease-in-out infinite;
}

@keyframes float {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-20px); }
}

.platform-info {
  padding: 60px;
  color: white;
  text-align: left;
  z-index: 1;
  position: relative;
}

.platform-logo {
  display: flex;
  align-items: center;
  margin-bottom: 40px;
}

.logo-text {
  font-size: 42px;
  font-weight: 700;
  background: linear-gradient(45deg, #fff, #e3f2fd);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.logo-badge {
  margin-left: 12px;
  padding: 4px 10px;
  background: rgba(255,255,255,0.2);
  border-radius: 12px;
  font-size: 14px;
  font-weight: 500;
  backdrop-filter: blur(10px);
}

.platform-slogan h2 {
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 16px;
  line-height: 1.4;
}

.platform-slogan p {
  font-size: 16px;
  opacity: 0.9;
  margin-bottom: 40px;
  line-height: 1.6;
}

.platform-features {
  display: flex;
  gap: 24px;
  flex-wrap: wrap;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 15px;
  font-weight: 500;
  padding: 8px 16px;
  background: rgba(255,255,255,0.15);
  border-radius: 20px;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.feature-item:hover {
  background: rgba(255,255,255,0.25);
  transform: translateY(-2px);
}

.feature-item .el-icon {
  font-size: 18px;
}

/* 右侧登录区域 */
.login-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30px;
  background: #f8f9fa;
  min-width: 0;
}

.login-panel {
  width: 100%;
  max-width: 420px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 8px 30px rgba(0,0,0,0.08);
  padding: 40px;
  transition: all 0.3s ease;
}

.login-panel:hover {
  box-shadow: 0 12px 40px rgba(0,0,0,0.12);
  transform: translateY(-5px);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h1 {
  font-size: 28px;
  color: #333;
  margin-bottom: 8px;
  font-weight: 600;
}

.login-header p {
  color: #666;
  font-size: 15px;
}

/* 表单样式 */
.login-form {
  margin-top: 20px;
}

.login-error {
  margin-bottom: 20px;
  animation: shake 0.5s;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
  20%, 40%, 60%, 80% { transform: translateX(5px); }
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 15px 0 25px;
}

.forgot-password {
  font-size: 14px;
}

.login-button {
  width: 100%;
  height: 48px;
  font-size: 16px;
  letter-spacing: 1px;
  margin-top: 10px;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(64, 158, 255, 0.3);
}

.caps-lock-warning {
  color: #E6A23C;
  font-size: 12px;
  margin-top: 5px;
  display: flex;
  align-items: center;
  gap: 5px;
}



.login-footer {
  margin-top: 30px;
  text-align: center;
  color: #999;
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .login-background {
    width: 50%;
  }
  
  .login-content {
    padding: 25px;
  }
  
  .login-panel {
    max-width: 400px;
    padding: 35px;
  }
}

@media (max-width: 1200px) {
  .login-background {
    width: 45%;
  }
  
  .platform-info {
    padding: 30px;
  }
  
  .platform-slogan h2 {
    font-size: 22px;
  }
  
  .login-content {
    padding: 20px;
  }
  
  .login-panel {
    max-width: 380px;
    padding: 30px;
  }
}

@media (max-width: 992px) {
  .login-background {
    width: 45%;
    min-width: 350px;
  }
  
  .platform-slogan h2 {
    font-size: 22px;
  }
  
  .logo-text {
    font-size: 36px;
  }
  
  .login-content {
    min-width: 350px;
    padding: 25px;
  }
  
  .login-panel {
    max-width: 380px;
    padding: 35px;
  }
}

@media (max-width: 768px) {
  .login-container {
    flex-direction: column;
  }
  
  .login-background {
    width: 100%;
    height: 280px;
    padding: 20px;
  }
  
  .platform-info {
    padding: 20px;
    text-align: center;
  }
  
  .platform-logo {
    justify-content: center;
    margin-bottom: 20px;
  }
  
  .platform-slogan h2 {
    font-size: 20px;
    margin-bottom: 10px;
  }
  
  .platform-slogan p {
    margin-bottom: 20px;
    font-size: 14px;
  }
  
  .platform-features {
    justify-content: center;
    margin-top: 15px;
    font-size: 14px;
    flex-wrap: wrap;
  }
  
  .login-panel {
    padding: 30px 20px;
    border-radius: 16px 16px 0 0;
    margin-top: -20px;
    box-shadow: 0 -8px 20px rgba(0,0,0,0.1);
  }
  
  .login-content {
    padding: 10px;
    background: white;
  }
  
  .login-button {
    height: 44px;
  }
  
  .login-header h1 {
    font-size: 24px;
  }
}

/* 小屏幕手机适配 */
@media (max-width: 480px) {
  .login-background {
    height: 240px;
    padding: 15px;
  }
  
  .platform-slogan h2 {
    font-size: 18px;
  }
  
  .platform-slogan p {
    font-size: 13px;
  }
  
  .logo-text {
    font-size: 32px;
  }
  
  .logo-badge {
    font-size: 12px;
    padding: 3px 8px;
  }
  
  .login-panel {
    padding: 25px 15px;
  }
  
  .login-options {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .feature-item {
    font-size: 12px;
    padding: 6px 12px;
  }
  
  .demo-account {
    font-size: 13px;
    padding: 6px 10px;
  }
}
</style>
